import service from '@/utils/request'

export async function hlogin(data: object) {
  return await service({
    url: `/rest/usr/hlogin`,
    method: 'post',
    withCredentials: true,
    data
  })
}

//获取用com.google.code.kaptcha生成的验证码，用户登录调用klogin
//kaptcha不使用JSession，缺点是不够简洁，后端需开启redis服务，也耗资源降速度
export async function getCaptch() {
  //1--raw Captcha图片数据在response data中
  //要求：前端服务器的地址为后端CORS接纳的特定origin(如http://localhost:8080)，
  //否则无法取得用户定义的response head(如challenge)
  var imgSrcData = await service({
    url: `/rest/usr/getCaptcha?${Math.random()}`,
    method: 'get',
    withCredentials: true,
    responseType: 'arraybuffer'
  }).then(res => {
    //  如使用了challenge，且challenge在response headers中
    if (typeof res.headers.challenge != "undefined" && res.headers.challenge != null)
      window.sessionStorage.setItem("challenge", res.headers.challenge);
    return 'data:image/png;base64,' + btoa(
      new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
    )
  })
  return imgSrcData    //<img src="data:image/jpg;base64,..."/img>\
}

export async function login(data: object) {
  return await service({
    url: `/rest/usr/login`,
    method: 'post',
    data
  })
}